package com.acme.serverside;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

class ClientConnection implements Runnable {

    public static final String EXIT = "<exit>";
    public static final String ONLINE = "online!";

    private final Socket socket;
    private ObjectOutputStream out;
    private ObjectInputStream in;
    private String nickName;

    public ClientConnection(Socket socket) {
        this.socket = socket;
        new Thread(this).start();
    }

    protected String getNickName() {
        return this.nickName;
    }

    private int setNickName(String nickName) {
        if (nickName == null)
            return 1;
        else if (nickName.isEmpty())
            return 2;
        else if (ControlMessaging.existsNickName(nickName))
            return 3;
        this.nickName = nickName;

        return 0;
    }


    private void validateNickName() throws Exception {
        sendMessage("Please, enter your nickname in jChat: ");
        int res;
        while ((res = setNickName((String) this.in.readObject())) != 0) {
            if (res == 3)
                sendMessage("This nick is already used!\n");
            else
                sendMessage("Incorrect nick!\n");
        }
        sendMessage(String.format("Welcome to jChat, %s!\n", this.nickName));
        ChatServer.sendAll(this.nickName, ONLINE);
    }


    private void messaging() throws IOException, ClassNotFoundException {
        String message;
        do {
            message = (String) this.in.readObject();
            ChatServer.sendAll(this.nickName, message);
        } while (!message.equals(EXIT));
        sendMessage(EXIT);
    }

    @Override
    public void run() {
        try (ObjectOutputStream out = new ObjectOutputStream(this.socket.getOutputStream());
             ObjectInputStream in = new ObjectInputStream(this.socket.getInputStream())) {
            this.in = in;
            this.out = out;
            validateNickName();
            messaging();
            ChatServer.clientDisconnecting(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void sendMessage(String message) throws IOException {
        if (this.out == null) {
            throw new NullPointerException("OUT is null!");
        }
        if (message == null || message.isEmpty()) {
            return;
        }
        this.out.writeObject(message);
    }

}
